//
//  MerchandiseSearchListController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/22.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "MerchandiseSearchListController.h"
#import "JFBLoadingAnimation.h"
#import "MerchandiseEditController.h"
#import "MerchandiseCell.h"
#import "BatchOptController.h"

@interface MerchandiseSearchListController ()<UISearchBarDelegate,JFBDataSourceRefreshDelegate,UIGestureRecognizerDelegate>
{
    NSInteger currentPage;
    NSInteger itemPerPage;
    NSInteger total;
    NSInteger up;
    NSInteger down;
    NSString *searchStr;
}




@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UIView *updownContainerView;
@property (nonatomic,strong) NSDictionary *dataDic;
@property (nonatomic,assign) NSInteger    currentIndex;


@end

@implementation MerchandiseSearchListController

- (NSDictionary*) dataDic{
    if (!_dataDic) {
        _dataDic = @{
                     @0 : [NSMutableArray array],
                     @1 : [NSMutableArray array],
                     @2 : [NSMutableArray array]
                     };
    }
    return _dataDic;
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.items = [@[] mutableCopy];
//    self.hidesBottomBarWhenPushed = true;
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"商品搜索";
    
    self.updownContainerView.hidden = YES;
   
    currentPage = 1;
    itemPerPage = 10;
    
    self.currentItems = [@[] mutableCopy];
    self.currentIndex = 0;
    
    [self setupUI];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
 [self.navigationItem setLeftBarButtonItem: [self createBackView]];
    
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(refreshTable)];
    [self.tableView.footer setTitle: @"已经没有更多的数据了" forState: MJRefreshFooterStateNoMoreData];
    self.tableView.hidden = true;
}

//- (void)reload:(__unused id)sender searchText:(NSString*)searchText {
//    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
//    [JFBMerchandiseDS search:^(NSArray *merchandiseList, NSUInteger onlineCount, NSUInteger offlineCount, NSError *error) {
//        [SVProgressHUD dismiss];
//        self.items = [@[] mutableCopy];
//        for( JFBMerchandiseDS *ds in merchandiseList ) {
//            [self.items addObject:ds];
//        }
//        self.upShelfLabel.text = [NSString stringWithFormat:@"已上架商品(%lu)", (unsigned long)onlineCount];
//        self.downShelfLabel.text = [NSString stringWithFormat:@"已下架商品(%lu)", (unsigned long)offlineCount];
////        [self refreshCount];
//        [self.tableView reloadData];
//    } name:searchText showType:0];
//}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.updownContainerView.hidden = NO;
    self.tableView.hidden = NO;
    [self.view setNeedsDisplay];
    searchStr = searchBar.text;
    [self reload:searchStr];
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) setupUI {
    //改变button的frame值跟下面label的frame值
    self.allRed.frame = CGRectMake(0, 41, screen_Width/3, 3);
    self.upRed.frame = CGRectMake(screen_Width/3, 41, screen_Width/3, 3);
    self.downRed.frame = CGRectMake((screen_Width/3)*2, 41, screen_Width/3, 3);
    //设置button的frame
    self.allShelfButtonClick.frame = CGRectMake(0, 0, screen_Width/3, 44);
    self.upShelfButtonClick.frame = CGRectMake(screen_Width/3, 0, screen_Width/3, 44);
    self.downShelfButtonClick.frame = CGRectMake((screen_Width/3)*2, 0, screen_Width/3, 44);
    //给三个button添加点击事件
    [self.allShelfButtonClick addTarget:self action:@selector(allShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
    [self.upShelfButtonClick addTarget:self action:@selector(upShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
    [self.downShelfButtonClick addTarget:self action:@selector(downShelfButtonClickTo) forControlEvents:UIControlEventTouchUpInside];
    //进来先隐藏已上架跟未上架的横条
    self.upRed.hidden = YES;
    self.downRed.hidden = YES;
    self.upShelfNumber.textColor = [UIColor grayColor];
//    self.upShelfLabel.textColor = [UIColor grayColor];
    self.downShelfNumber.textColor = [UIColor grayColor];
    self.downShelfLabel.textColor = [UIColor grayColor];
    
    [self allShelfButtonClickTo];
    

    
    UITapGestureRecognizer *upGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onUpLabelClick:)];
    self.upShelfLabel.userInteractionEnabled=YES;
    upGesture.numberOfTapsRequired=1;
    //设置手指数 单指
    upGesture.numberOfTouchesRequired=1;
    // titleLabel添加手势识别
    [self.upShelfLabel addGestureRecognizer:upGesture];
    
    UITapGestureRecognizer *downGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onDownLabelClick:)];
    self.downShelfLabel.userInteractionEnabled=YES;
    downGesture.numberOfTapsRequired=1;
    //设置手指数 单指
    downGesture.numberOfTouchesRequired=1;
    // titleLabel添加手势识别
    [self.downShelfLabel addGestureRecognizer:downGesture];
    
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
}
- (void)reload{
    [self reload:searchStr];
}
- (void)reload:(NSString *)searchStr {
    [self.dataDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, NSMutableArray * _Nonnull obj, BOOL * _Nonnull stop) {
        [obj removeAllObjects];
    }];
    NSInteger tempCurrentPage = currentPage;
    if(currentPage>1){
        
        itemPerPage = currentPage*itemPerPage;
        currentPage = 1;
        
    }
    
    [self loadDataForWeb:searchStr];
    currentPage =tempCurrentPage;
    itemPerPage = 10;
}
-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) loadDataForWeb:(NSString *)searchStr {
    
    JFBLoadingAnimation *animation = [[JFBLoadingAnimation alloc] init:self.tableView];
    NSDictionary *parameter = @{@"mpName":searchStr,
                                @"currentPage":[NSNumber numberWithInteger:currentPage],
                                @"itemsPerPage":[NSNumber numberWithInteger:itemPerPage],
                                @"ut":[[NSUserDefaults standardUserDefaults]objectForKey:@"ut"]};
    [[JFBAPIClient sharedClient:true] GET:@"/back-product/getMerchantProductList.do" parameters:parameter success:^(NSURLSessionDataTask *task, id JSON) {
        [animation stop];
        [self.items removeAllObjects];
        if([JSON[@"code"] integerValue] == 0) {
            
            NSDictionary *data = [JSON valueForKey:@"data"];
            total = [[data valueForKeyPath:@"total"] integerValue];
            up = [[data valueForKeyPath:@"shelvesNum"] integerValue];
            down = [[data valueForKeyPath:@"pullOffShelvesNum"] integerValue];
            
            NSArray *response  = [data valueForKeyPath:@"merchantProductList"];
            NSArray *array =[NSArray yy_modelArrayWithClass:[JFBMerchandiseDS class] json:response];
            [self.items addObjectsFromArray:array];
            
            [self commonDataDic];
            
        }else if ([JSON[@"code"] integerValue] == 99){
            UIViewController* viewController;
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [animation stop];
    }];
}


- (void) refreshTable{
    currentPage++;
    [self loadDataForWeb:searchStr];
    [self.tableView.footer endRefreshing];
    
}
- (void) commonDataDic{
    [(NSMutableArray*)self.dataDic[@0] addObjectsFromArray:self.items];
    for( JFBMerchandiseDS *ds in self.items) {
        if( ds.mpStatus == 4) {
            [(NSMutableArray*)self.dataDic[@1] addObject:ds];
        }else{
            [(NSMutableArray*)self.dataDic[@2] addObject:ds];
        }
    }
    [self refreshCount];
    [self.tableView reloadData];
    
}
-(void)refreshCount{
    self.allShelfNumber.text = [NSString stringWithFormat:@"%ld",total];
    self.upShelfNumber.text = [NSString stringWithFormat:@"%ld",up];
    self.downShelfNumber.text = [NSString stringWithFormat:@"%ld",down];
    
}

- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}
#pragma mark -点击全部
-(void)allShelfButtonClickTo{
    if (self.currentFilter == 4 && self.currentFilter == 5) {//全部
        [self.allShelfButtonClick setSelected:true];
        self.currentFilter = 6;
    }else if (self.currentFilter == 4){//上架
        [self.upShelfButtonClick setSelected:false];
        [self.downShelfButtonClick setSelected:false];
        self.currentFilter = 6;
    }else{//下架
        [self.allShelfButtonClick setSelected:true];
        [self.downShelfButtonClick setSelected:false];
        [self.upShelfButtonClick setSelected:false];
        self.currentFilter = 6;
    }
    self.allShelflabel.textColor = [UIColor redColor];
    self.allShelfNumber.textColor = [UIColor redColor];
    self.allRed.hidden = NO;
    self.upShelfNumber.textColor = [UIColor grayColor];
    self.upShelfLabel.textColor = [UIColor grayColor];
    self.upRed.hidden = YES;
    self.downShelfNumber.textColor = [UIColor grayColor];
    self.downShelfLabel.textColor = [UIColor grayColor];
    self.downRed.hidden = YES;
    
    self.currentIndex = 0;
    //    [self commonDataDic];
    [self.tableView reloadData];
}
#pragma mark -点击已上架
-(void)upShelfButtonClickTo{
    if (self.currentFilter == 6) {//全部
        [self.upShelfButtonClick setSelected:true];
        self.currentFilter = 4;
    }else if (self.currentFilter == 4){//上架
        [self.upShelfButtonClick setSelected:false];
        self.currentFilter = 4;
    }else{//下架
        [self.upShelfButtonClick setSelected:true];
        [self.downShelfButtonClick setSelected:false];
        self.currentFilter = 4;
    }
    
    self.currentIndex = 1;
    [self.tableView reloadData];
    
    //    [self commonDataDic];
    
    self.allShelflabel.textColor = [UIColor grayColor];
    self.allShelfNumber.textColor = [UIColor grayColor];
    self.allRed.hidden = YES;
    self.upShelfNumber.textColor = [UIColor redColor];
    self.upShelfLabel.textColor = [UIColor redColor];
    self.upRed.hidden = NO;
    self.downShelfNumber.textColor = [UIColor grayColor];
    self.downShelfLabel.textColor = [UIColor grayColor];
    self.downRed.hidden = YES;
}
#pragma mark -点击未上架
-(void)downShelfButtonClickTo{
    if( self.currentFilter == 6 ) {
        [self.downShelfButtonClick setSelected:true];
        self.currentFilter = 5;
    }else if( self.currentFilter == 4 ) {
        [self.upShelfButtonClick setSelected:false];
        [self.downShelfButtonClick setSelected:true];
        self.currentFilter = 5;
    }else {
        [self.downShelfButtonClick setSelected:false];
        self.currentFilter = 5;
    }
    self.currentIndex = 2;
    [self.tableView reloadData];
    //    [self commonDataDic];
    self.allShelflabel.textColor = [UIColor grayColor];
    self.allShelfNumber.textColor = [UIColor grayColor];
    self.allRed.hidden = YES;
    self.upShelfNumber.textColor = [UIColor grayColor];
    self.upShelfLabel.textColor = [UIColor grayColor];
    self.upRed.hidden = YES;
    self.downShelfNumber.textColor = [UIColor redColor];
    self.downShelfLabel.textColor = [UIColor redColor];
    self.downRed.hidden = NO;
}
//商品的上下架
- (void)clickCellUpDownBtnWithCell:(MerchandiseCell*)cell Mode:(JFBMerchandiseDS *)mode
{
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
    [JFBMerchandiseDS switchUpAndDownShelf:^(BOOL isSuccess, NSError *error) {
        [SVProgressHUD dismiss];
        if( isSuccess ) {
            [JFBUIAnimation alertTips:@"修改成功"];
            [self reload:searchStr];
        }
    } merchandiseID:mode.mpId oldStatus:mode.mpStatus newStatus: mode.mpStatus==4? 5 :4 saleType:mode.saleType];
    
}


#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [(NSMutableArray*)self.dataDic[@(self.currentIndex)] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    JFBMerchandiseDS * ds = [(NSMutableArray*)self.dataDic[@(self.currentIndex)] objectAtIndex:indexPath.row];
    MerchandiseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"merchandiseCellIdentifier" forIndexPath:indexPath];
    UISwitch *shelfSwitch = [cell viewWithTag:10086];
    if(ds.saleType==3){
        shelfSwitch.hidden = YES;
    }
    
    
    cell.merchandise = ds;
    [cell setClickUpDown:^(MerchandiseCell *cell,JFBMerchandiseDS *mode) {
        [self clickCellUpDownBtnWithCell:cell Mode:mode];
        
        shelfSwitch.selected = !shelfSwitch.selected;
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _currentMerchandise = [self.dataDic[@(self.currentIndex)] objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:@"merchandiseEditIdentifier" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if( [segue.identifier isEqualToString:@"merchandiseEditIdentifier"] ) {
        MerchandiseEditController * controller = (MerchandiseEditController*)segue.destinationViewController;
        controller.hidesBottomBarWhenPushed = true;
        controller.merchandise = _currentMerchandise;
        controller.delegate = self;
    } else if( [segue.identifier isEqualToString:@"batchOptIdentifier"] ) {
        BatchOptController * controller = (BatchOptController*)segue.destinationViewController;
        controller.items = self.items;
        controller.delegate = self;
    }
}


@end
